#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <windows.h>

typedef struct {
    char name[20];
    char position[20];
    char jobtitle[20];
    char num[15];
    char email[50]; 
} people;

// 显示联系人信息
void xianshi(people *total, int count) {
    int i;
    for (i = 0; i < count; i++) {
        printf("%-15s", total[i].name);
        printf("%-15s", total[i].position);
        printf("%-15s", total[i].jobtitle);
        printf("%-15s", total[i].num);
        printf("%-15s\n", total[i].email);
    }
}

// 添加联系人
void tianjia(people **total, int *count) {
    *count += 1;
    *total = (people *)realloc(*total, (*count) * sizeof(people));
    if (*total == NULL) {
        printf("内存分配失败，请检查系统内存是否充足!");
        printf("请在5秒后重试！");
        Sleep(5000);
        system("cls");
        return;
    }
    printf("请输入您想添加联系人的姓名：");
    scanf("%s", (*total)[*count - 1].name);
    printf("请输入您想添加联系人的职位：");
    scanf("%s", (*total)[*count - 1].position);
    printf("请输入您想添加联系人的职称：");
    scanf("%s", (*total)[*count - 1].jobtitle);
    printf("请输入您想添加联系人的电话号码：");
    scanf("%s", (*total)[*count - 1].num);
    printf("请输入您想添加联系人的邮箱：");     
    scanf("%s", (*total)[*count - 1].email);
    system("cls");
}

// 删除联系人
void shanchu(people **total, int *count) {
    int i; 
    char delate[30]; 
    int k; 
    int found = 0;
    if (*total == NULL) {
        printf("您的通讯录内没有联系人，无法进行删除！");
        printf("请在5秒后重新做出选择！");
        Sleep(5000);
        system("cls");
        return;
    }
    printf("请您选择您想要删除联系人的信息：(人名，职位，职称，电话号及邮箱等)");
    scanf("%s", delate);
    for (i = 0; i < *count; i++) {
        if (strcmp((*total)[i].name, delate) == 0 ||
            strcmp((*total)[i].position, delate) == 0 ||
            strcmp((*total)[i].jobtitle, delate) == 0 ||
            strcmp((*total)[i].num, delate) == 0 ||
            strcmp((*total)[i].email, delate) == 0) {
            for (k = i; k < *count - 1; k++) {
                (*total)[k] = (*total)[k + 1];
            }
            *count -= 1;
            *total = (people *)realloc(*total, (*count) * sizeof(people));
            if (*total == NULL) {
                printf("内存释放出错,或您的联系人为空！");
                Sleep(5000);
                system("cls");
                return;
            }
            found = 1;
            break;
        }
    }
    if (found == 0) {
        printf("对不起，没有找到该联系人，请检查信息输入！\n");
        printf("请在5秒后重新选择操作！");
        Sleep(5000);
        system("cls");
    }
    if (found == 1) {
        printf("删除成功，将在五秒后返回主页面！");
        Sleep(5000);
        system("cls");
    }
}

// 修改联系人信息
void xiugai(people *total, int count) {
	if (total == NULL){
		printf("没有联系人无法进行修改！");
		system("pause");
		system("cls");
		return;
	}
    char name[20];
    printf("请输入您要修改的联系人姓名：");
    scanf("%s", name);
    int found = 0;
    int i; 
    for (i = 0; i < count; i++) {
        if (strcmp(total[i].name, name) == 0) {
            printf("找到联系人：%s\n", total[i].name);
            printf("请输入新的职位：");
            scanf("%s", total[i].position);
            printf("请输入新的职称：");
            scanf("%s", total[i].jobtitle);
            printf("请输入新的电话号码：");
            scanf("%s", total[i].num);
            printf("请输入新的邮箱：");
            scanf("%s", total[i].email);
            found = 1;
            system("pause");
            system("cls"); 
            break;
        }
    }
    if (!found) {
        printf("未找到该联系人!\n");
        Sleep(5000);
        system("cls");
    }
}

// 查找联系人
void chazhao(people *total, int count) {
    if (count == 0) {
        printf("没有联系人信息可供查找!\n");
        Sleep(5000);
        system("cls");
        return;
    }
    char search[20];
    printf("请输入您想要查找的信息:");
    scanf("%s", search);
    int found = 0;
    int i;
    for (i = 0; i < count; i++) {
        if (strcmp(total[i].name, search) == 0 ||
            strcmp(total[i].position, search) == 0 ||
            strcmp(total[i].jobtitle, search) == 0 ||
            strcmp(total[i].num, search) == 0 ||
            strcmp(total[i].email, search) == 0) {
            printf("%-10s", total[i].name);
            printf("%-10s", total[i].position);
            printf("%-10s", total[i].jobtitle);
            printf("%-10s", total[i].num);
            printf("%-10s\n", total[i].email);
            found = 1;
        }
    }
    if (found) {
        printf("请及时保存数据，按任意键返回主界面！");
        system("pause");
        system("cls");
    }
    if (!found) {
        printf("未找到该联系人!\n");
        Sleep(5000);
        system("cls");
    }
}

// 对联系人按姓名排序
void paixu(people *total, int count) {
	if (total == NULL){
		printf("结构体为空时无法排序！");
		system("pause");
		system("cls");
		return;
	}
    int i, j;
    for (i = 0; i < count - 1; i++) {
        for (j = 0; j < count - i - 1; j++) {
            if (strcmp(total[j].name, total[j + 1].name) > 0) {
                people temp = total[j];
                total[j] = total[j + 1];
                total[j + 1] = temp;
            }
        }
    }
    system("cls");
}

// 保存通讯录到文件
void baocun(people *total, int count) {
    FILE *file;
    // 当 total 为空时，直接清空文件
    if (total == NULL) {
        int choice;
        printf("您的通讯录为空，继续操作将会清空通讯录文件！");
        printf("输入 1 确认清空，输入其他任意键确认返回！");
        if (scanf("%d", &choice) != 1) {
            // 处理输入非整数的情况
            while (getchar() != '\n');
            choice = 0;
        }
        if (choice == 1) {
            file = fopen("contacts.txt", "w");
            if (file == NULL) {
                printf("无法打开文件进行清空操作！\n");
                Sleep(5000);
                system("cls");
                return;
            }
            fclose(file);
            printf("通讯录文件已清空！\n");
        }
        system("pause");
        system("cls");
        return;
    }

    int choice;
    printf("请注意，您的数据将会覆盖文件上的数据！\n");
    printf("请您确认：\n");
    printf("1. 直接覆盖  2. 返回  3. 合并数据\n");
    if (scanf("%d", &choice) != 1) {
        // 处理输入非整数的情况
        while (getchar() != '\n');
        choice = 0;
    }

    switch (choice) {
        case 1:
            file = fopen("contacts.txt", "w");
            if (file == NULL) {
                printf("无法打开文件进行保存！\n");
                Sleep(5000);
                system("cls");
                return;
            }
            int i; 
            for (i = 0; i < count; i++) {
                fprintf(file, "%s %s %s %s %s\n", total[i].name, total[i].position, total[i].jobtitle, total[i].num, total[i].email);
            }
            fclose(file);
            printf("通讯录已保存到文件！\n");
            Sleep(5000);
            system("cls");
            break;
        case 2:
            system("cls");
            break;
        case 3: {
            file = fopen("contacts.txt", "a");
            if (file == NULL) {
                printf("无法打开文件进行合并操作！\n");
                Sleep(5000);
                system("cls");
                return;
            }
            int i;
            for (i = 0; i < count; i++) {
                fprintf(file, "%s %s %s %s %s\n", total[i].name, total[i].position, total[i].jobtitle, total[i].num, total[i].email);
            }
            fclose(file);
            printf("通讯录已合并保存到文件！\n");
            Sleep(5000);
            system("cls");
            break;
        }
        default:
            printf("无效的选择！");
            system("pause");
            system("cls");
            break;
    }
}
// 从文件加载通讯录
void jiazai(people **total, int *count) {
    FILE *file = fopen("contacts.txt", "r");
    if (file == NULL) {
        printf("无法打开文件进行加载!\n");
        Sleep(5000);
        system("cls");
        return;
    }
    int chose = 0;
    if (*total != NULL) {
        printf("您正在编辑的文档不为空！\n");
        printf("如果您想直接加载的话，将会丢失您现在的数据！\n");
        printf("请您为您的数据做出选择！\n");
        printf("1.直接覆盖（请确保您的数据已经保存或备份）  2.返回主页面   3.将您的数据和文档合并\n");
        while (chose != 1 && chose != 2 && chose != 3) {
            scanf("%d", &chose);
            while (getchar() != '\n'); // 清理输入缓冲区
        }
    } else {
        chose = 1;
    }
    switch (chose) {
        case 1:
            *count = 0;
            char name[20], position[20], jobtitle[20], num[15], email[50];
            while (fscanf(file, "%s %s %s %s %s", name, position, jobtitle, num, email) == 5) {
                *total = (people *)realloc(*total, (*count + 1) * sizeof(people));
                if (*total == NULL) {
                    printf("内存分配失败!\n");
                    fclose(file);
                    return;
                }
                strcpy((*total)[*count].name, name);
                strcpy((*total)[*count].position, position);
                strcpy((*total)[*count].jobtitle, jobtitle);
                strcpy((*total)[*count].num, num);
                strcpy((*total)[*count].email, email);
                (*count)++;
            }
            fclose(file);
            printf("通讯录已从文件加载!\n");
            Sleep(5000);
            system("cls");
            break;
        case 2:
            fclose(file);
            system("cls"); 
            return;
        case 3:
            while (fscanf(file, "%s %s %s %s %s", name, position, jobtitle, num, email) == 5) {
                *total = (people *)realloc(*total, (*count + 1) * sizeof(people));
                if (*total == NULL) {
                    printf("内存分配失败!\n");
                    fclose(file);
                    return;
                }
                strcpy((*total)[*count].name, name);
                strcpy((*total)[*count].position, position);
                strcpy((*total)[*count].jobtitle, jobtitle);
                strcpy((*total)[*count].num, num);
                strcpy((*total)[*count].email, email);
                (*count)++;
            }
            fclose(file);
            printf("通讯录已从文件加载并合并!\n");
            Sleep(5000);
            system("cls");
            break;
        default:
            printf("无效的选择！");
            system("pause");
            system("cls");
    }
}

int main(int argc, char *argv[]) {
    int choise = 0;
    int count = 0;
    people *total = NULL;
    printf("您好，欢迎进入通讯管理系统！\n");
    while (choise != 8) {
        printf("通讯录：\n");
        xianshi(total, count);
        if (total == NULL) {
            printf("NULL\n");
        }
        printf("请选择您想要进行的服务：\n");
        printf("1.添加联系人\n2.删除联系人\n3.查找内容\n4.修改联系人\n5.排序联系人\n6.保存通讯录\n7.加载通讯录\n8.退出通讯录 \n"); 
        scanf("%d", &choise);
        while (getchar() != '\n'); // 清理输入缓冲区
        switch (choise) {
            case 1:
                tianjia(&total, &count);
                choise = 0;
                break;
            case 2:
                shanchu(&total, &count);
                choise = 0;
                break;
            case 3:
                chazhao(total, count);
                choise = 0;
                break;
            case 4:
                xiugai(total, count);
                choise = 0;
                break;
            case 5:
                paixu(total, count);
                choise = 0;
                break;
            case 6:
                baocun(total, count);
                choise = 0;
                break;
            case 7:
                jiazai(&total, &count);
                choise = 0;
                break;
            case 8:
                printf("即将退出系统，欢迎再次使用！\n");
                Sleep(5000);
                system("cls");
                break;
            default:
                printf("无效的选择\n");
                system("pause");
                system("cls");
        }
    }
    if (total != NULL) {
        free(total);
    }
    return 0;
}